import { RightOutlined, UserOutlined } from '@ant-design/icons';
import { Dropdown, Layout, Menu } from "antd";
import React, { useCallback, useContext, useEffect, useMemo, useReducer } from 'react';
import { useParams, useSearchParams } from "react-router-dom";
import About from '../components/About';
import FillTabs from '../components/FillTabs';
import client from '../utils/client';
import { setCookie } from '../utils/cookie';
import styles from './home.module.css';
import Page from './Page';
import { SessionContext } from './Session';

function Home() {
  const { sys } = useParams();
  const [searchParams] = useSearchParams();
  const logout = useContext(SessionContext);
  const SYS = sys.toUpperCase();

  const [state, dispatch] = useReducer((state, action) => {
    switch (action.type) {
      case 'sys.change':
        return { ...state, selectedKey: action.key, selectedSys: state.user.子系统.find(s => s.ID === action.key), menu_item_lock: false, menu_item_current: null };
      case 'menu.load':
        return { ...state, menu: action.menu };
      case 'menu.enter':
        return { ...state, menu_item_current: state.menu_item_lock ? state.menu_item_current : action.item };
      case 'menu.leave':
        return { ...state, menu_item_current: state.menu_item_lock ? state.menu_item_current : null }
      case 'menu.click':
        return { ...state, menu_item_current: action.item, menu_item_lock: !state.menu_item_lock || state.menu_item_current !== action.item };
      case 'tabs.open':
        let [opened] = state.tabs.filter(t => t.key === action.tab.key);
        if (opened) {
          return { ...state, menu_hidden: true, tabs_activeKey: opened.key, menu_item_current: null };
        } else {
          return { ...state, menu_hidden: true, tabs: [...state.tabs, action.tab], tabs_activeKey: action.tab.key, menu_item_current: null };
        }
      case 'tabs.change':
        return { ...state, menu_hidden: true, tabs_activeKey: action.key };
      case 'tabs.close':
        let close_index = -1;
        let rest_tabs = state.tabs.filter((t, i) => {
          if (t.key === action.key) close_index = i;
          return t.key !== action.key;
        });
        let tabs_activeKey = action.key === state.tabs_activeKey ? rest_tabs.length === 0 ? null : rest_tabs.at(Math.max(0, close_index - 1)).key : state.tabs_activeKey;
        return { ...state, tabs: rest_tabs, tabs_activeKey, menu_hidden: !!tabs_activeKey };
      case 'navigator.click':
        return { ...state, menu_hidden: false, menu_expand: !state.menu_hidden ? !state.menu_expand : true, menu_item_lock: false, menu_item_current: null };
      default:
        return state;
    }
  }, {
    title: client.get('system')?.名称,
    logo: client.get('system')?.图标地址,
    user: client.get('user'),
    sys_items: client.get('user').子系统.map(m => ({
      key: m.ID,
      label: m.简称 + (m.缩写 ? '(' + m.缩写 + ')' : ''),
      onClick: () => dispatch({ type: 'sys.change', key: m.ID }),
    })),
    org_items: client.get('user').机构.map(org => ({
      key: org.ID,
      label: org.名称路径,
      disabled: true,
    })).concat([{
      key: Date.now() + 1,
      label: '常用资源',
      onClick: () => open({
        名称: '常用资源',
        ID: 'e39f41a8af8447fcb8498ae9b424c3c8',
        页面: 'e39f41a8af8447fcb8498ae9b424c3c8',
      })
    }, {
      key: Date.now() + 2,
      label: '修改密码',
      onClick: () => open({
        名称: '修改密码',
        ID: 'adf01ff31e924aeb80e32fbcf877bfd8',
        页面: 'adf01ff31e924aeb80e32fbcf877bfd8',
      })
    }, {
      key: Date.now() + 3,
      label: '注 销',
      onClick: logout
    }]),
    selectedKey: null,
    selectedSys: null,
    tabs: [],
    tabs_activeKey: null,
    menu: [],
    menu_hidden: false,
    menu_expand: true,
    menu_item_current: null,
    menu_item_lock: false,
  });

  document.title = state.title;

  const header = useMemo(() => (
    <div className={styles.header}>
      <div className={styles.title}>
        {!state.logo ? null : <img alt="logo" src={state.logo} />}
        <span>{state.title}</span>
      </div>
      <div className={styles.menu}>
        {SYS === 'MP' ? <Menu mode="horizontal" theme="dark" items={state.sys_items} selectedKeys={[state.selectedKey]} /> : null}
      </div>
      <div className={styles.user}>
        <Dropdown menu={{ items: state.org_items }}>
          <div><UserOutlined /> {state.user.名称}</div>
        </Dropdown>
      </div>
    </div>
  ), [SYS, state.logo, state.org_items, state.selectedKey, state.sys_items, state.title, state.user.名称]);

  const open = useCallback((item, e) => {
    if (e && (e.ctrlKey || e.altKey || e.shiftKey)) {
      // 在新窗口或新标签页中打开
      setCookie('mp.token', client.get('TOKEN'));
      let a = document.createElement('a');
      a.setAttribute('href', `#/${sys}/page/${item.页面}`);
      a.setAttribute('target', "_blank");
      a.click();
    } else {
      dispatch({
        type: 'tabs.open',
        tab: {
          key: item.ID,
          label: item.名称,
          children: <Page id={item.页面} menuId={item.ID} args={item.args} tabs={{
            open(id, title, args) {
              open({ ID: String(Date.now() * Math.random()), 页面: id, 名称: title, args });
            },
            close() {
              dispatch({ type: 'tabs.close', key: item.ID });
            },
          }} />
        }
      });
    }
  }, [sys]);

  useEffect(() => {
    dispatch({ type: 'sys.change', key: SYS === 'MP' ? (state.user.子系统[0] || {}).ID : (state.user.子系统.find(s => s.缩写 === SYS) || {}).ID });
  }, [SYS, state.user.子系统]);

  useEffect(() => {
    if (!state.selectedKey) return;
    const key = `menu_${state.user.ID}_${state.selectedKey}`;
    if (client.has(key)) {
      dispatch({ type: 'menu.load', menu: client.get(key) });
      return;
    };
    client.job('B.SystemMenuGet', { ID: state.selectedKey }).then(menu => {
      client.set(key, menu);
      dispatch({ type: 'menu.load', menu });
    });
  }, [state.selectedKey, state.user]);

  return (
    <Layout className={styles.container}>
      {
        // 支持URL中?max=1参数控制隐藏标题栏实现全屏效果
        searchParams.get("max") ? null : <Layout.Header>{header}</Layout.Header>
      }
      <Layout.Content className={styles.content}>
        <FillTabs type="editable-card" size="small" hideAdd activeKey={state.tabs_activeKey} items={state.tabs}
          onEdit={(targetKey, action) => action === 'remove' ? dispatch({ type: 'tabs.close', key: targetKey }) : null}
          onTabClick={key => dispatch({ type: 'tabs.change', key })}
          tabBarExtraContent={{
            left: <div className={styles.navigator_button} onClick={() => dispatch({ type: 'navigator.click' })}> == 首页导航 == </div>
          }}
        />
        {state.menu_hidden ? null : <Layout className={styles.navigator}>
          {
            !state.menu_expand ? null : (
              <Layout.Sider>
                <div className={styles.navigator_list}>
                  {
                    state.menu.map(item => (
                      <div key={item.ID} className={"menu-item-lv1" + (item === state.menu_item_current ? ' menu-item-lv1-current' : '')}
                        onClick={() => dispatch({ type: 'menu.click', item: item })}
                        onTouchEnd={() => dispatch({ type: 'menu.click', item: item })}
                        onMouseEnter={() => dispatch({ type: 'menu.enter', item: item })}
                        onMouseLeave={() => dispatch({ type: 'menu.leave' })}
                      >
                        <span>{item.名称}</span>
                        <RightOutlined />
                      </div>
                    ))
                  }
                </div>
              </Layout.Sider>
            )
          }

          <Layout.Content>
            <div className="mp-home-page">
              {state.selectedSys && state.selectedSys.首页页面 ? <Page key={state.selectedSys.首页页面}
                id={state.selectedSys.首页页面} tabs={{
                  open(id, title, args) {
                    open({ ID: String(Date.now() * Math.random()), 页面: id, 名称: title, args });
                  },
                  close(id) {
                    dispatch({ type: 'tabs.close', key: id });
                  },
                }} /> : <About />}
            </div>

            <div hidden={!state.menu_item_current} className={styles.navigator_popup}
              onMouseEnter={() => dispatch({ type: 'menu.enter', item: state.menu_item_current })}
              onMouseLeave={() => dispatch({ type: 'menu.leave' })}>
              {
                (!state.menu_item_current || !state.menu_item_current.children) ? null : state.menu_item_current.children.map(menu => (
                  <div key={menu.ID} className="menu-item-lv2">
                    <div className="menu-item-lv2-title" title={menu.名称}>
                      {menu.名称}
                    </div>
                    <div className="menu-item-lv2-content">
                      {
                        !menu.children ? null : menu.children.map(sub_menu => (
                          <div key={sub_menu.ID} className="menu-item-lv3" title={sub_menu.名称}
                            onClick={(e) => open(sub_menu, e)}>
                            {sub_menu.名称}
                          </div>
                        ))
                      }
                    </div>
                  </div>
                ))
              }
              <div className={styles.navigator_footer}>小技巧: 按住Alt点击菜单可以在新窗口打开</div>
            </div>

          </Layout.Content>
        </Layout>
        }
      </Layout.Content>
    </Layout>
  );
}

export default Home;